package com.sm.honkon.app.utils

import android.util.Log
import com.TreeMap
import me.hgj.jetpackmvvm.ext.util.TAG
import java.net.URLEncoder
import java.text.SimpleDateFormat
import java.util.*
import com.codec.binary.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

/**
 * @description
 * @author csw
 * @date 2021-06-24
 */
object SendCodeHelper {
    const val ACCESS_KEY_ID = "LTAI5t8uxRiDfMx1fRo7Qf5H"
    const val ACCESS_KEY_SECRET = "z3xJfNnjNQqfqoDPP9FHr9mKnwFRfg"
    const val SIGN_NAME = "深圳华莱医疗技术有限公司"
    const val TEMPLATE_CODE = "SMS_214605168"


    fun createUrl(phone: String,code:String): String {
        return TreeMap<String, String>().let {
            val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
            df.timeZone = SimpleTimeZone(0, "GMT") // 这里一定要设置GMT时区

            it["SignatureMethod"] = "HMAC-SHA1"
            it["SignatureNonce"] = UUID.randomUUID().toString()
            it["AccessKeyId"] = ACCESS_KEY_ID
            it["SignatureVersion"] = "1.0"
            it["Timestamp"] = df.format(Date())
            it["Action"] = "SendSms"
            it["Version"] = "2017-05-25"
            it["PhoneNumbers"] = phone
            it["TemplateParam"]= "{\"code\":\"$code\"}"
            it["SignName"] = SIGN_NAME
            it["TemplateCode"] = TEMPLATE_CODE
            val sortQueryStringTmp = StringBuilder()
            val itKeys = it.keys.iterator()
            while (itKeys.hasNext()) {
                val key = itKeys.next()
                sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=")
                    .append(specialUrlEncode(it[key]!!));
            }
            val sortedQueryString = sortQueryStringTmp.substring(1) // 去除第一个多余的&符号
            val stringToSign = StringBuilder()
            stringToSign.append("GET").append("&")
            stringToSign.append(specialUrlEncode("/")).append("&")
            stringToSign.append(specialUrlEncode(sortedQueryString))
            val sign = sign("$ACCESS_KEY_SECRET&", stringToSign.toString())
            Log.e(TAG, "createUrl: $stringToSign")
            val signature: String = specialUrlEncode(sign)
            "https://dysmsapi.aliyuncs.com/?Signature=$signature$sortQueryStringTmp"
        }
    }

    private fun sign(accessSecret: String, stringToSign: String): String {
        val mac = Mac.getInstance("HmacSHA1")
        mac.init(SecretKeySpec(accessSecret.toByteArray(charset("UTF-8")), "HmacSHA1"))
        val signData = mac.doFinal(stringToSign.toByteArray(charset("UTF-8")))
        return Base64.encodeBase64String(signData)
    }

    private fun specialUrlEncode(value: String): String {
        return URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A")
            .replace("%7E", "~")
    }
}